<template>
	<view class="login">
		<view class="content winapp">
			<!-- 头部logo -->
			<view class="header">
				<image :src="logoImage"></image>
			</view>
			<!-- 主体表单 -->
			<view class="main">
				<wInput v-model="userid" type="text"  placeholder="用户名" :focus="isFocus"></wInput>
				<wInput v-model="password" type="password"  placeholder="密码"></wInput>
			</view>
			<wButton class="wbutton" text="登 录" :rotate="isRotate" bgColor="#005495" @click="startLogin"></wButton>
			
			<!-- 底部信息 -->
			<view class="footer">
				<!-- <navigator url="forget" open-type="navigate">找回密码</navigator> -->
				<view class="">
					<text style="width: 100%;"  v-show="showDownloadpercent">正在下载（{{downloadpercent}}）</text>
				</view>
				<view class="">
					<text style="width: 100%;" >WCS {{environment}} · 版本号：{{version}}</text>
				</view>
				<!-- <navigator url="register" open-type="navigate">注册账号</navigator> -->
			</view>
		</view>
		<u-overlay :show="showOverlay">
		</u-overlay>
		<esunMask :showMask="showMask"></esunMask>
	</view>
</template>

<script>
	let _this;
	function parentMethod() {
	    console.log('这是父页面的方法');
	}
	import wInput from '../../components/watch-login/watch-input.vue' //input
	import wButton from '../../components/watch-login/watch-button.vue' //button
	import esunMask from '../../components/esun-mask/esun-mask.vue' 
	import logo from 'static/wcslogo.png'

	export default {
		data() {
			return {
				usermsg: {},
				baseUrl: '',
				configUrl: '',
				localUrl: '',
				nacosFlag: false,
				localNacos: false,
				version: '',
				logoImage: logo,
				userid: '', //用户/电话
				password: '', //密码
				isRotate: false, //是否加载旋转
				isFocus: true, // 是否聚焦,
				thisview: null,
				mrsUrl:'',
				apkUrl:'',
				downloadpercent:'',
				showDownloadpercent:false,
				environment:'',
				mrs2: '',
				showOverlay: false,
				showMask: false
			};
		},
		components: {
			wInput,
			wButton,
			esunMask
		},
		mounted() {
			_this = this;
			_this.baseUrl = _this.$store.getters.getBaseUrl
			_this.environment = _this.$store.getters.getEnvironment
			_this.version = _this.$store.getters.getVersion
			uni.removeStorageSync('network')
			uni.removeStorageSync('usermsg')
		},
		ons() {
		},
		onLoad() {
			try{
				this.thisview = plus.webview.currentWebview();
			}catch(e){
				//TODO handle the exception
			}
			// console.log(uni.getSystemInfoSync().platform);
			// if(uni.getSystemInfoSync().platform !=='windows'){
			// 	this.thisview = plus.webview.currentWebview();
			// }
		},
		methods: {
			chkVersion(){
				_this.mrsHttp({
					url: _this.baseUrl + '/GetVersion',
					method: 'post',
					data: {
						domain:''
					},
					success: e => {
						console.log(e)
						if (res.code === "100000") {
							if(_this.version !== res.result){
								uni.showModal({
									title: '提示',
									cancelText:'取消',
									confirmText:'确定',
									content: '服务器存在新版本，是否更新？',
									success: function(res) {
										if (res.confirm) {
											_this.isRotate = false;
											_this.downloadAPK()
										} else if (res.cancel) {
											_this.isRotate = false;
											console.log('用户点击取消');
										}
									}
								});
							}
							
							return
						}
						if (res.code !== '100000') {
							uni.showToast({
								icon: 'none',
								title: res.resultMsg
							})
							return
						}
					},
					fail: e => {
						console.log('fali');
					}
				});
			},
			downloadAPK() {
				var url = _this.apkUrl;
				var dtask = plus.downloader.createDownload(url, {}, function(d, status) {
					if(status == 200) { // 下载成功
						var path = d.filename;
						console.log(d.filename);
						plus.runtime.install(path); // 安装下载的apk文件
					} else { //下载失败
						uni.showToast({
							icon: 'none',
							position: 'bottom',
							title: '下载失败'
						});
						//document.getElementById("total_zhebiceng").stylresisplay = "none";
					}
				});
				_this.showDownloadpercent = true
				dtask.addEventListener("statechanged", function() {
					_this.downloadpercent = parseInt(dtask.downloadedSize / dtask.totalSize * 100) + '%';
					if(_this.downloadpercent === '100%') {
						uni.showToast({
							icon: 'none',
							position: 'bottom',
							title: '下载成功'
						});
					}
				}, true);
				dtask.start();
			},
			goToMenu(data) {
				let paramsString = "/pages/menu/index?data=" + data + "&userid=" + _this.userid
				uni.navigateTo({
					url: paramsString,
				})
			},
			goToChangePassWord(data) {
				_this.isRotate = false;
				let paramsString = "/pages/login/forget?data=" + data + "&name=" + _this.userid
				uni.navigateTo({
					url: paramsString
				})
			},
			parentMethod() {
			    console.log('这是父页面的方法');
			},
			async startLogin(e) {
				console.log(e)
				console.log('this', this)
				//登录
				if (this.isRotate) {
					//判断是否加载中，避免重复点击请求
					return false;
				}
				if (this.userid.length == "") {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '用户名不能为空'
					});
					return;
				}
				if (this.password.length < 1) {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '密码不正确'
					});
					return;
				}

				var call_starttime = _this.appUtil.getCurrentTime()
				try {
					_this.isRotate = true
					// _this.showMask = true
					const res = await new Promise((resolve, reject) => {
						_this.mrsHttp({
							// url: _this.baseUrl + '/logon',
							url: _this.baseUrl + '/api/SysAuth/APPLogin',
							method: 'post',
							data: {
								account: _this.userid,
								corp: '',
								password: _this.password,
								userLang: 'ch',
								version: _this.version,
								environment: _this.environment,
								source: "APP"
							},
							success: res => {
								_this.isRotate = false;
								console.log('res', res)
								var call_apitime = _this.appUtil.getCurrentTime()
								if (!res) {
									_this.appUtil.beep()
									uni.showToast({
										icon: 'none',
										title: '服务器异常'
									})
									return
								}

								if (res.code === 200) {
									_this.nacosFlag = false

									this.$store.dispatch('setUserid', _this.userid)
									this.$store.dispatch('setLanguage', 'ch')
									this.$store.dispatch('setCorp', '')
									this.$store.dispatch('setToken', res.result.accessToken)

									_this.usermsg = {};
									_this.usermsg.sessionid = res.result.accessToken
									_this.usermsg.userid = _this.userid
									uni.setStorageSync('usermsg',JSON.stringify(_this.usermsg));
									_this.goToMenu(res.result)
									return
								}
								else {
									_this.appUtil.beep()
									uni.showToast({
										icon: 'none',
										title: res.message
									})
									return
								}
							},
							fail: e => {
								_this.isRotate = false;
								_this.appUtil.beep()
								var call_apitime = _this.appUtil.getCurrentTime()
								var ui_outtime = _this.appUtil.getCurrentTime()
								_this.appUtil.ajaxLog('logon', _this.userid, '', '', '', call_starttime, call_apitime, ui_outtime, '登录fail' + JSON.stringify(e), new Date().getTime())
								
								console.log('fali');
							}
						});
					});
				} catch (e) {
					console.log(e)
				} finally {
					console.log('finally')
					_this.isRotate = false
					_this.showMask = false

				}

			}
		}
	}
</script>

<style>
	@import url("../../components/watch-login/css/icon.css");
	@import url("./css/main.css");
	@import url("../../static/css/base.css");
</style>
